package org.cosmact.designer.vxml.gefeditor.router;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.cosmact.vxml.model.Dialog;
import org.cosmact.vxml.model.DialogConnection;

public class Router {

    private final Dialog head;

    private List<Path> pathes = new ArrayList<Path>();

    public Router(final Dialog head) {
	if (head == null)
	    throw new IllegalArgumentException("Head for a router");
	this.head = head;
	pathes.clear();
	Path path = new Path(head);
	pathes.add(path);
	route(path);
    }

    private void route(final Path path) {
	int number = 0;
	Path copy = path.getCopy();// Keep original path
	for (DialogConnection connection : path.getLastNode()
		.getSourceConnections()) {
	    if (number == 0) {
		// append the new node
		path.appendNode(connection.getTarget());
	    } else {
		// create new path based path
		Path newPath = copy.getCopy();
		newPath.appendNode(connection.getTarget());
		pathes.add(newPath);
	    }
	    number++;
	}

	// The pathes maybe changed when loop. So iterater on the copy array to
	// avoid
	// ConcurrentModifiedException.
	for (Path nowPath : pathes.toArray(new Path[0])) {
	    if (nowPath.isEnd()) {
		continue;
	    }
	    route(nowPath);
	}
    }

    public List<Path> getPathes() {
	return Collections.unmodifiableList(pathes);
    }

    public Dialog getHead() {
	return head;
    }
}
